package com.ruoyi.circle.service.impl;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.*;
import java.time.LocalTime;

import com.ruoyi.circle.dao.ICircleStatisticsDao;
import com.ruoyi.circle.domain.CircleMemberRelation;
import com.ruoyi.circle.domain.CircleTagsRel;
import com.ruoyi.circle.mapper.CircleMemberRelationMapper;
import com.ruoyi.circle.mapper.CircleTagsRelMapper;
import com.ruoyi.circle.dao.ICircleMemberRelationDao;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.digest.mapper.HsGeneratedTextMapper;
import com.ruoyi.pushRecord.domain.CircleHsPushRecord;
import com.ruoyi.pushRecord.mapper.CircleHsPushRecordMapper;
import com.ruoyi.pushSetting.dao.ICircleHsPushSettingDao;
import com.ruoyi.pushSetting.domain.CircleHsPushSetting;
import com.ruoyi.pushSetting.mapper.CircleHsPushSettingMapper;
import com.ruoyi.question.domain.QuestionInfo;
import com.ruoyi.question.mapper.QuestionInfoMapper;
import com.ruoyi.tag.domain.TagsInfo;
import com.ruoyi.tag.mapper.TagsInfoMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.circle.mapper.CircleBasicInfoMapper;
import com.ruoyi.circle.domain.CircleBasicInfo;
import com.ruoyi.circle.service.ICircleBasicInfoService;
import org.springframework.transaction.annotation.Transactional;

/**
 * 圈子基础信息Service业务层处理
 *
 * @author 区嘉盛
 * @date 2025-06-09
 */
@Service
public class CircleBasicInfoServiceImpl implements ICircleBasicInfoService {
    @Autowired
    private CircleBasicInfoMapper circleBasicInfoMapper;

    @Autowired
    private CircleMemberRelationMapper circleMemberRelationMapper;

    @Autowired
    private CircleTagsRelMapper circleTagsRelMapper;

    @Autowired
    private TagsInfoMapper tagsInfoMapper;

    @Autowired
    private ICircleMemberRelationDao circleMemberRelationDao;

    @Autowired
    private ICircleStatisticsDao circleStatisticsDao;

    @Autowired
    private ICircleHsPushSettingDao circleHsPushSettingDao;

    @Autowired
    private CircleHsPushSettingMapper circleHsPushSettingMapper;

    @Autowired
    private HsGeneratedTextMapper hsGeneratedTextMapper;

    @Autowired
    private CircleHsPushRecordMapper circleHsPushRecordMapper;

    @Autowired
    private QuestionInfoMapper questionInfoMapper;

    /**
     * 查询圈子基础信息
     *
     * @param id 圈子基础信息主键
     * @return 圈子基础信息
     */
    @Override
    public CircleBasicInfo selectCircleBasicInfoById(Long id) {
        CircleBasicInfo circleBasicInfo = circleBasicInfoMapper.selectCircleBasicInfoById(id);
        if (circleBasicInfo != null) {
            List<Long> tagIds = circleTagsRelMapper.selectTagIdsByCircleId(id);
            circleBasicInfo.setTagIds(tagIds.toArray(new Long[0]));
            List<TagsInfo> tagList = new ArrayList<>();
            if (!tagIds.isEmpty()) {
                for (Long tagId : tagIds) {
                    TagsInfo tagsInfo = tagsInfoMapper.selectTagsInfoById(tagId);
                    if (tagsInfo != null) {
                        tagList.add(tagsInfo);
                    }
                }
            }
            circleBasicInfo.setTagList(tagList);
        }
        return circleBasicInfo;
    }

    /**
     * 查询圈子基础信息列表
     *
     * @param circleBasicInfo 圈子基础信息
     * @return 圈子基础信息
     */
    @Override
    public List<CircleBasicInfo> selectCircleBasicInfoList(CircleBasicInfo circleBasicInfo) {
        List<CircleBasicInfo> circleList;
        if (circleBasicInfo.getTagIds() != null && circleBasicInfo.getTagIds().length > 0) {
            circleList = circleBasicInfoMapper.selectCircleBasicInfoListByTags(circleBasicInfo, circleBasicInfo.getTagIds());
        } else {
            circleList = circleBasicInfoMapper.selectCircleBasicInfoList(circleBasicInfo);
        }
        for (CircleBasicInfo circle : circleList) {
            CircleMemberRelation param = new CircleMemberRelation();
            param.setCircleId(circle.getId());
            param.setMemberRole(3);
            param.setMemberStatus(1);
            List<CircleMemberRelation> ownerList = circleMemberRelationMapper.selectCircleMemberList(param);
            if (ownerList != null && !ownerList.isEmpty()) {
                circle.setOwnerUser(ownerList.get(0).getNickName());
            }
        }
        return circleList;
    }

    /**
     * 新增圈子基础信息
     *
     * @param circleBasicInfo 圈子基础信息
     * @return 结果
     */
    @Override
    @Transactional
    public int insertCircleBasicInfo(CircleBasicInfo circleBasicInfo) {
        if (circleBasicInfo.getApprovalStatus() == null) {
            circleBasicInfo.setApprovalStatus(1L);
        }
        int rows = circleBasicInfoMapper.insertCircleBasicInfo(circleBasicInfo);
        insertCircleTagsRel(circleBasicInfo);
        if (rows > 0) {
            Long userId = SecurityUtils.getUserId();
            circleMemberRelationDao.addCircleMember(circleBasicInfo.getId(), userId, 2);
            circleStatisticsDao.updateCircleHeatScore(circleBasicInfo.getId());

            // 自动配置圈子热搜推送设置
            if (circleBasicInfo.getApprovalStatus() == 1L) {
                createDefaultPushSetting(circleBasicInfo.getId(), circleBasicInfo.getCreatedBy());
            }
        }
        return rows;
    }

    /**
     * 修改圈子基础信息
     *
     * @param circleBasicInfo 圈子基础信息
     * @return 结果
     */
    @Override
    @Transactional
    public int updateCircleBasicInfo(CircleBasicInfo circleBasicInfo) {
        circleTagsRelMapper.deleteCircleTagsRelByCircleId(circleBasicInfo.getId());
        insertCircleTagsRel(circleBasicInfo);
        return circleBasicInfoMapper.updateCircleBasicInfo(circleBasicInfo);
    }

    /**
     * 批量删除圈子基础信息
     *
     * @param ids 需要删除的圈子基础信息主键
     * @return 结果
     */
    @Override
    @Transactional
    public int deleteCircleBasicInfoByIds(Long[] ids) {
        for (Long id : ids) {
            circleTagsRelMapper.deleteCircleTagsRelByCircleId(id);
            circleMemberRelationMapper.deleteCircleMemberRelationByCircleId(id);
            circleHsPushSettingMapper.deleteCircleHsPushSettingByCircleId(id);
        }
        return circleBasicInfoMapper.deleteCircleBasicInfoByIds(ids);
    }

    /**
     * 删除圈子基础信息信息
     *
     * @param id 圈子基础信息主键
     * @return 结果
     */
    @Override
    @Transactional
    public int deleteCircleBasicInfoById(Long id) {
        circleTagsRelMapper.deleteCircleTagsRelByCircleId(id);
        circleMemberRelationMapper.deleteCircleMemberRelationByCircleId(id);
        circleHsPushSettingMapper.deleteCircleHsPushSettingByCircleId(id);
        return circleBasicInfoMapper.deleteCircleBasicInfoById(id);
    }

    /**
     * 新增圈子标签关联信息
     *
     * @param circleBasicInfo 圈子基础信息对象
     */
    private void insertCircleTagsRel(CircleBasicInfo circleBasicInfo) {
        Long[] tagIds = circleBasicInfo.getTagIds();
        if (tagIds != null && tagIds.length > 0) {
            List<CircleTagsRel> relList = new ArrayList<>();
            for (Long tagId : tagIds) {
                CircleTagsRel rel = new CircleTagsRel();
                rel.setCircleId(circleBasicInfo.getId());
                rel.setTagId(tagId);
                relList.add(rel);
            }
            circleTagsRelMapper.batchInsertCircleTagsRel(relList);
        }
    }

    /**
     * 检查并删除没有标签关联的圈子
     *
     * @param circleId 圈子ID
     */
    @Override
    public void checkAndDeleteCircleWithoutTags(Long circleId) {
        int tagCount = circleTagsRelMapper.checkCircleHasTags(circleId);
        if (tagCount == 0) {
            circleBasicInfoMapper.deleteCircleBasicInfoById(circleId);
        }
    }

    /**
     * 普通用户申请新建圈子
     *
     * @param circleBasicInfo 圈子基础信息
     * @return 结果
     */
    @Override
    @Transactional
    public int applyCircle(CircleBasicInfo circleBasicInfo) {
        circleBasicInfo.setApprovalStatus(0L);
        int rows = circleBasicInfoMapper.insertCircleBasicInfo(circleBasicInfo);
        insertCircleTagsRel(circleBasicInfo);
        if (rows > 0) {
            Long userId = SecurityUtils.getUserId();
            circleMemberRelationDao.addCircleMember(circleBasicInfo.getId(), userId, 3);
        }
        return rows;
    }

    /**
     * 管理员审批圈子申请
     *
     * @param id       圈子ID
     * @param status   审批状态 1-已通过 2-已拒绝
     * @param approver 审批人
     * @return 结果
     */
    @Override
    @Transactional
    public int approveCircle(Long id, Long status, String approver) {
        CircleBasicInfo circleBasicInfo = new CircleBasicInfo();
        circleBasicInfo.setId(id);
        circleBasicInfo.setApprovalStatus(status);
        circleBasicInfo.setUpdatedBy(approver);
        int result = circleBasicInfoMapper.updateCircleBasicInfo(circleBasicInfo);
        if (result > 0 && status == 1L) {
            Long userId = SecurityUtils.getUserId();
            circleMemberRelationDao.addCircleMember(id, userId, 2);
            circleStatisticsDao.updateCircleHeatScore(id);

            // 审批通过时，自动配置圈子热搜推送设置
            createDefaultPushSetting(id, approver);
        }
        return result;
    }

    /**
     * 获取热门圈子列表
     *
     * @return 热门圈子列表
     */
    @Override
    public List<CircleBasicInfo> getHotCircle() {
        return circleBasicInfoMapper.getHotCircle();
    }

    /**
     * 根据用户选择的标签将用户加入到相应的圈子中
     *
     * @param userId 用户ID
     * @param tagIds 标签ID数组
     */
    @Override
    public void addUserToCirclesByTags(Long userId, Long[] tagIds) {
        // 存储已处理的圈子ID，避免重复添加
        Set<Long> processedCircleIds = new HashSet<>();

        // 遍历用户选择的每个标签
        for (Long tagId : tagIds) {
            // 查找包含该标签的所有圈子
            List<Long> circleIds = circleTagsRelMapper.selectCircleIdsByTagId(tagId);

            // 将用户添加到每个匹配的圈子中
            for (Long circleId : circleIds) {
                // 避免重复处理同一个圈子
                if (!processedCircleIds.contains(circleId)) {
                    // 添加用户到圈子，设置角色为会员(1)
                    circleMemberRelationDao.addCircleMember(circleId, userId, 1);
                    processedCircleIds.add(circleId);
                }
            }
        }
    }

    /**
     * 新增圈子标签关联
     *
     * @param circleTagsRel 圈子标签关联信息
     * @return 结果
     */
    @Override
    public int insertCircleTagsRel(CircleTagsRel circleTagsRel) {
        return circleTagsRelMapper.insertCircleTagsRel(circleTagsRel);
    }

    /**
     * 创建默认的圈子热搜推送设置
     *
     * @param circleId 圈子ID
     * @param creator  创建人
     */
    private void createDefaultPushSetting(Long circleId, String creator) {
        // 检查是否已存在该圈子的推送设置
        CircleHsPushSetting query = new CircleHsPushSetting();
        query.setCircleId(circleId);
        List<CircleHsPushSetting> existingSettings = circleHsPushSettingDao.selectCircleHsPushSettingList(query);

        // 如果不存在，则创建默认设置
        if (existingSettings == null || existingSettings.isEmpty()) {
            CircleHsPushSetting pushSetting = new CircleHsPushSetting();
            pushSetting.setCircleId(circleId);
            pushSetting.setPushTime(LocalTime.of(8, 0, 0));
            pushSetting.setPushStatus(1L);
            pushSetting.setCreatedBy(creator);
            pushSetting.setCreatedTime(LocalDate.now());
            pushSetting.setDeletedFlag(0L);

            circleHsPushSettingDao.insertCircleHsPushSetting(pushSetting);
        }
    }

    /**
     * 获取圈子当天全部的热搜推送内容与题目推送内容
     *
     * @param circleId 圈子ID
     * @return 热搜推送内容列表，每项包含摘要和文章，与题目推送内容
     */
    @Override
    public Map<String, Object> getLatestCircleHotSearchContent(Long circleId) {
        // 获取当天日期
        LocalDate today = LocalDate.now();
        LocalDateTime startOfDay = today.atStartOfDay();
        LocalDateTime endOfDay = today.atTime(23, 59, 59);

        // 查询当天的推送记录
        CircleHsPushRecord query = new CircleHsPushRecord();
        query.setCircleId(circleId);
        query.setPushStatus(1L); // 成功推送的记录
        List<CircleHsPushRecord> records = circleHsPushRecordMapper.selectCircleHsPushRecordList(query);

        // 筛选当天的记录
        List<CircleHsPushRecord> todayRecords = records.stream()
                .filter(record -> {
                    LocalDateTime pushTime = record.getPushTime();
                    return pushTime != null &&
                            !pushTime.isBefore(startOfDay) &&
                            !pushTime.isAfter(endOfDay);
                })
                .toList();

        // 处理记录并返回结果
        return processCircleHotSearchRecords(todayRecords);
    }

    /**
     * 获取所有圈子列表
     *
     * @return 所有圈子列表
     */
    @Override
    public List<CircleBasicInfo> getAllCircle() {
        return circleBasicInfoMapper.getAllCircle();
    }

    /**
     * 批量新增圈子标签关联
     *
     * @param circleTagsRelList 圈子标签关联列表
     * @return 结果
     */
    @Override
    public int insertBatchCircleTagsRel(List<CircleTagsRel> circleTagsRelList) {
        int result = 0;
        for (CircleTagsRel circleTagsRel : circleTagsRelList) {
            result = circleTagsRelMapper.insertCircleTagsRel(circleTagsRel);
        }
        return result;
    }

    /**
     * 获取我创建的圈子列表
     *
     * @param createUserId 创建用户ID
     * @return 我创建的圈子列表
     */
    @Override
    public List<CircleBasicInfo> getCircleCreatedByMe(Long createUserId) {
        return circleBasicInfoMapper.getCircleCreatedByMe(createUserId);
    }

    /**
     * 获取我加入的圈子列表
     *
     * @param userId 用户ID
     * @return 我加入的圈子列表
     */
    @Override
    public List<CircleBasicInfo> getJoinedCircle(Long userId) {
        return circleBasicInfoMapper.getJoinedCircle(userId);
    }

    /**
     * 获取我待审批的圈子列表
     *
     * @param createUserId 创建用户ID
     * @return 待审批的圈子列表
     */
    @Override
    public List<CircleBasicInfo> getMyApprovalCircle(Long createUserId) {
        return circleBasicInfoMapper.getMyApprovalCircle(createUserId);
    }

    /**
     * 获取圈子全部的热搜推送内容与题目推送内容
     *
     * @param circleId 圈子ID
     * @return 热搜推送内容列表，每项包含摘要和文章，与题目推送内容
     */
    @Override
    public Map<String, Object> getAllCircleHotSearchContent(Long circleId) {
        // 查询所有的推送记录
        CircleHsPushRecord query = new CircleHsPushRecord();
        query.setCircleId(circleId);
        query.setPushStatus(1L); // 成功推送的记录
        List<CircleHsPushRecord> records = circleHsPushRecordMapper.selectCircleHsPushRecordList(query);

        // 处理记录并返回结果
        return processCircleHotSearchRecords(records);
    }

    /**
     * 根据圈子名称查询圈子
     *
     * @param circleName 圈子名称
     * @return 圈子列表
     */
    @Override
    public List<CircleBasicInfo> queryCircleByCircleName(String circleName) {
        return circleBasicInfoMapper.queryCircleByCircleName(circleName);
    }

    /**
     * 根据标签ID查询圈子
     *
     * @param tagId 标签ID
     * @return 圈子列表
     */
    @Override
    public List<CircleBasicInfo> getCircleByTagId(Long tagId) {
        return circleBasicInfoMapper.getCircleByTagId(tagId);
    }

    /**
     * 处理圈子热搜推送记录与题目推送记录，提取内容并构建结果
     *
     * @param records 推送记录列表
     * @return 包含内容列表的结果Map
     */
    private Map<String, Object> processCircleHotSearchRecords(List<CircleHsPushRecord> records) {
        Map<String, Object> result = new HashMap<>();
        List<Map<String, Object>> contentList = new ArrayList<>();

        if (records == null || records.isEmpty()) {
            result.put("contentList", contentList);
            return result;
        }

        // 处理每条记录
        for (CircleHsPushRecord record : records) {
            // 获取主题ID
            Long topicId = record.getTopicId();
            if (topicId == null) {
                continue;
            }

            // 获取AI生成的内容
            Map<String, String> contentMap;
            if (record.getGeneratedTextId() != null) {
                // 如果有生成文本ID，直接通过ID查询
                contentMap = hsGeneratedTextMapper.selectContentById(record.getGeneratedTextId());
            } else {
                // 否则通过主题ID查询
                contentMap = hsGeneratedTextMapper.selectContentByTopicId(topicId);
            }

            if (contentMap != null && !contentMap.isEmpty()) {
                Map<String, Object> content = new HashMap<>();
                content.put("generatedTitle", contentMap.get("generatedTitle"));
                content.put("summaryContent", contentMap.get("summaryContent"));
                content.put("generatedArticle", contentMap.get("generatedArticle"));
                content.put("pushTime", record.getPushTime());
                content.put("topicId", topicId);
                content.put("recordId", record.getId());

                // 获取与该推送内容关联的题目信息
                Long generatedTextId = record.getGeneratedTextId();
                if (generatedTextId != null) {
                    // 查询与该生成文本关联的题目
                    QuestionInfo queryParam = new QuestionInfo();
                    queryParam.setGeneratedTextId(generatedTextId);
                    queryParam.setQuestionStatus(1L); // 只查询启用状态的题目
                    List<QuestionInfo> questionList = questionInfoMapper.selectQuestionInfoList(queryParam);

                    // 提取题目的部分信息
                    List<Map<String, Object>> questions = new ArrayList<>();
                    for (QuestionInfo question : questionList) {
                        Map<String, Object> questionMap = new HashMap<>();
                        questionMap.put("questionId", question.getId());
                        questionMap.put("questionTitle", question.getQuestionTitle());
                        questionMap.put("questionType", question.getQuestionType());
                        questionMap.put("questionOptions", question.getQuestionOptions());
                        questionMap.put("correctAnswer", question.getCorrectAnswer());
                        questionMap.put("answerExplanation", question.getAnswerExplanation());
                        questionMap.put("rewardPoints", question.getRewardPoints());
                        questions.add(questionMap);
                    }

                    // 将题目信息添加到内容中
                    content.put("questions", questions);
                }

                contentList.add(content);
            }
        }

        // 将内容列表添加到结果中
        result.put("contentList", contentList);
        return result;
    }

}
